import axios from 'axios'
import { Message, Loading } from 'element-ui'

// 全局loading
var loading = null
var requestCount = 0

const startLoading = () => {
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    background: 'rgba(0, 0, 0, 0.8)'
  })
}

// const endLoading = () => {
//   setTimeout(() => {
//     loading.close()
//   }, 500)
// }

const showFullScreenLoading = () => {
  requestCount === 0 && startLoading()
  requestCount++
}

const tryHideFullScreenLoading = () => {
  if (requestCount <= 0) return
  requestCount--
  requestCount === 0 && endLoading()
}

// 获取token
const getToken = () => `${window.localStorage.getItem('token')}`

const instance = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 600000,
  // withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
    Authorization: getToken()
  }
})

// 塞值到token
instance.setToken = (token) => {
  instance.defaults.headers.Authorization = `Bearer ${token}`
  window.localStorage.setItem('token', token)
}

// 无痛刷新
const refreshToken = () => {}

// 错误处理
const error = (error) => {
  if (error.response) {
    const { status } = error.response
    const errorDesc = {
      400: '请求失败',
      401: '请重新登录',
      403: '您没有访问权限',
      404: '没有对应模块，请检查链接地址',
      500: '服务器错误，请联系开发人员'
    }
    if (status === 401) {
      return refreshToken()
    }
    if (status !== 200) {
      // notification.error({
      //   message: errorDesc[status],
      //   description: msg
      // })
      Message({
        type: 'error',
        message: errorDesc[status]
      })
      endLoading()
    }
  }
  return Promise.reject(error)
}

// 请求拦截
instance.interceptors.request.use(config => {
  config.loading && showFullScreenLoading()
  if (config.method === 'post') {
    if (config.data) {
      config.data.token = getToken()
      config.data.openid = getToken()
    } else {
      config.data = {
        token: getToken(),
        openid: getToken()
      }
    }
  }
  return config
}, error)

// 返回拦截
instance.interceptors.response.use(response => {
  const { status, msg } = response.data
  status === 200 && Message({
    type: 'success',
    message: msg
  })
  tryHideFullScreenLoading()
  return response.data
}, error)

export default instance
